// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const userId = wxContext.OPENID
  
  try {
    const { recordId, recordData } = event

    console.log('保存记录云函数被调用:', {
      recordId,
      recordData,
      userId
    })

    // 确保记录数据包含用户ID和时间戳
    const now = new Date()
    recordData.user_id = userId
    recordData.updated_at = now

    // 如果有 date_str，也保存一个 Date 对象用于兼容
    if (recordData.date_str) {
      const [year, month, day] = recordData.date_str.split('-').map(Number)
      recordData.date = new Date(year, month - 1, day, 0, 0, 0, 0)
    }
    
    // 如果是更新记录
    if (recordId) {
      // 先检查记录是否属于当前用户
      const record = await db.collection('daily_records')
        .doc(recordId)
        .get()
      
      if (!record.data || record.data.user_id !== userId) {
        return {
          status: 'error',
          message: '记录不存在或无权修改'
        }
      }
      
      // 更新记录
      await db.collection('daily_records')
        .doc(recordId)
        .update({
          data: recordData
        })
      
      return {
        status: 'success',
        data: {
          _id: recordId
        }
      }
    } 
    // 如果是新建记录
    else {
      // 检查是否已存在该日期的记录
      const date = new Date(recordData.date)
      const nextDay = new Date(date)
      nextDay.setDate(date.getDate() + 1)
      
      const existingRecords = await db.collection('daily_records')
        .where({
          user_id: userId,
          date: _.gte(date).and(_.lt(nextDay))
        })
        .get()
      
      // 如果已存在记录，则更新
      if (existingRecords.data.length > 0) {
        const existingRecord = existingRecords.data[0]
        
        await db.collection('daily_records')
          .doc(existingRecord._id)
          .update({
            data: recordData
          })
        
        return {
          status: 'success',
          data: {
            _id: existingRecord._id
          }
        }
      } 
      // 否则创建新记录
      else {
        recordData.created_at = now
        
        const result = await db.collection('daily_records')
          .add({
            data: recordData
          })
        
        return {
          status: 'success',
          data: {
            _id: result._id
          }
        }
      }
    }
  } catch (err) {
    return {
      status: 'error',
      message: err.message,
      error: err
    }
  }
} 